<template >
  <basiccard :header_nav="header_nav">
    <!-- 提示消息 -->
    <el-alert title="消息提示的文案" type="info" show-icon center></el-alert>
    <!-- 步骤条 -->
    <el-steps :space="210" :active="parseInt(activeIndex)" finish-status="success" align-center>
      <el-step title="基本属性"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
    <!-- 任务栏 -->
    <el-form
      :model="addForm"
      :rules="addFormrules"
      ref="addFormRef"
      label-width="100px"
      label-position="top"
    >
      <el-tabs
        v-model="activeIndex"
        :tab-position="'left'"
        style="height: 900px;"
        :before-leave="tabLeave"
        @tab-click="tabClick"
      >
        <el-tab-pane label="基本属性" name="0">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input v-model="addForm.goods_price" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input v-model="addForm.goods_number" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input v-model="addForm.goods_weight " type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader
              expand-trigger="hover"
              :options="cateList"
              :props="cateProps"
              v-model="addForm.goods_cat"
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">
          <el-form-item
            :label="item.attr_name"
            v-for="(item) in manyTableData "
            :key="item.attr_id"
          >
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox
                border
                :label="itemcheck"
                v-for="(itemcheck,i) in item.attr_vals"
                :key="i"
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品属性" name="2">
          <el-form-item :label="item.attr_name" v-for="(item) in onlyTableData" :key="item.attr_id">
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <el-upload
            :action="uploadUrl"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture"
            :headers="headersObj"
            :on-success="uploadSuccess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <quill-editor v-model="addForm.goods_introduce"></quill-editor>
          <el-button type="primary" @click="add">添加商品</el-button>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <!-- 图片预览 -->
    <el-dialog title="图片" :visible.sync="ImgVisible" width="50%">
      <img :src="previewPath" alt class="previewImg" />
    </el-dialog>
  </basiccard>
</template>
<script>
import _ from 'lodash'
export default {

  name: "Add",
  data() {
    return {
      header_nav: {
        path: "/welecome",
        rolesMge: "商品管理",
        rolesList: "添加商品"
      },
      previewPath: "",
      ImgVisible: false,
      headersObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      // 图片上传地址
      uploadUrl: "http://127.0.0.1:8888/api/private/v1/upload",
      //   tabActive:'0',
      activeIndex: "0",
      //   表单验证对象
      addFormrules: {
        goodsname: [
          { required: true, message: "请输入商品名称", trigger: "blur" }
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" }
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" }
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" }
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" }
        ]
      },
      //   表单绑定对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        // 所属分类
        goods_cat: [],
        // 图片数组
        pics: [],
        // 商品的详情描述
        goods_introduce: '""',
        attrs:[]
      },
      //   动态参数列表
      manyTableData: [],
      // 静态参数列表
      onlyTableData: [],
      //   商品分类
      cateList: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      }
    };
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error("获取分类失败");
      this.cateList = res.data;
    },
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    tabLeave(activeName, oldName) {
      if (oldName == "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    async tabClick() {
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.getcateId}/attributes`,
          {
            params: {
              sel: "many"
            }
          }
        );
        if (res.meta.status !== 200) return this.$message.error("获取失败");
        console.log(res.data);
        this.manyTableData = res.data;
        this.manyTableData.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
      } else if (this.activeIndex === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.getcateId}/attributes`,
          {
            params: {
              sel: "only"
            }
          }
        );
        if (res.meta.status !== 200) return this.$message.error("获取失败");
        console.log(22);

        console.log(res.data);
        this.onlyTableData = res.data;
      }
    },
    // 点击文件的狗子
    handlePreview(file) {
      console.log(file);
      this.previewPath = file.response.data.url;
      this.ImgVisible = true;
    },
    // 移除文件的狗子
    handleRemove(file) {
      console.log(file.response.data.tmp_path);
      const filepath = file.response.data.tmp_path;
      const i = this.addForm.pics.findIndex(x => {
        x.pic === filepath;
      });
      this.addForm.pics.splice(i, 1);
      console.log(this.addForm);
    },
    // 上传文件成功的狗子
    uploadSuccess(res) {
      console.log(res.data);
      this.addForm.pics.push({ pic: res.data.tmp_path });
      console.log(this.addForm);
    },
   add() {
      console.log(1);
      
      this.$refs.addFormRef.validate( async valid=>{
        if(!valid){
          return this.$message.error('填写必要的表单项')
        }
      
        //  取出数组的数据
        // 动态参数
        this.manyTableData.forEach(item=>{
               const newInfo = {attr_id:item.attr_id,
               attr_value:item.attr_vals.join(' ')}
               this.addForm.attrs.push(newInfo)
        })
        // 静态属性
           this.onlyTableData.forEach(item=>{
              const newInfo = {attr_id:item.attr_id,
               attr_value:item.attr_vals}
               this.addForm.attrs.push(newInfo)
           })

          // 深度克隆
          console.log(1);
          
         let form  = _.cloneDeep(this.addForm)
       form.goods_cat =   form.goods_cat.join(',')
       console.log(form);

      const {data:res} =await this.$http.post('goods',form)
      if(res.meta.status!==201) return this.$message.error('添加数据失败')
      this.$message.success('添加成功')
      this.$router.push('/goods')
       
      })
    }
  },
  computed: {
    getcateId() {
      if (this.addForm.goods_cat.length == 3) {
        return this.addForm.goods_cat[2];
      }
    }
  },
  created() {
    this.getCateList();
  }
};
</script>
<style lang="scss" scoped>
.el-steps {
  margin-top: 20px;
  margin-bottom: 20px;
}
.el-checkbox {
  margin-left: 0 !important;
}
.previewImg {
  width: 100%;
}
.ql-editor {
  min-height: 300px;
}
.el-button {
  margin-top: 15px;
}
</style>